package com.chucang.shucang.ttp.nftcenter.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

public class AvataUtils {

    /**
     * 对请求参数进行签名处理
     *
     * @param path      请求路径
     * @param query     Query 参数,需转为 Map 格式
     * @param body      Body 参数，需转为 Map 格式
     * @param timestamp 当前时间戳（毫秒）
     * @param apiSecret 应用方的 API Secret
     * @return 返回签名结果
     */
    public static String signRequest(String path, Map<String, Object> query, Map<String, Object> body, long timestamp, String apiSecret) {
        Map<String, Object> paramsMap = new HashMap<>();

        paramsMap.put("path_url", path);

        if (query != null && !query.isEmpty()) {
            query.forEach((key, value) -> paramsMap.put("query_" + key, value));
        }

        if (body != null && !body.isEmpty()) {
            body.forEach((key, value) -> paramsMap.put("body_" + key, value));
        }

        // 将请求参数序列化为排序后的 JSON 字符串
        String jsonStr = JSON.toJSONString(paramsMap, SerializerFeature.MapSortField);

        // 执行签名
        return sha256Sum(jsonStr + timestamp + apiSecret);
    }

    /**
     * SHA256 摘要
     *
     * @param str s
     * @return s
     */
    private static String sha256Sum(String str) {
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            // Should not happen
            e.printStackTrace();
        }
        assert digest != null;
        byte[] encodedHash = digest.digest(str.getBytes(StandardCharsets.UTF_8));
        return bytesToHex(encodedHash);
    }

    /**
     * 将 bytes 转为 Hex
     *
     * @param hash h
     * @return s
     */
    private static String bytesToHex(byte[] hash) {
        StringBuilder hexString = new StringBuilder(2 * hash.length);
        for (byte b : hash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}
